package com.pethospital.servlet;

import com.pethospital.entity.HealthRecord;
import com.pethospital.entity.PageResult;
import com.pethospital.entity.Pet;
import com.pethospital.entity.User;
import com.pethospital.service.HealthRecordService;
import com.pethospital.service.PetService;
import com.pethospital.service.impl.HealthRecordServiceImpl;
import com.pethospital.service.impl.PetServiceImpl;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.math.BigDecimal;
import java.net.URLEncoder;
import java.sql.Date;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 健康记录控制器
 * Health Record Controller
 * 
 * @author PetHospital System
 * @version 1.0
 */
public class HealthRecordServlet extends HttpServlet {
    
    private HealthRecordService healthRecordService = new HealthRecordServiceImpl();
    private PetService petService = new PetServiceImpl();
    
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) 
            throws ServletException, IOException {
        doPost(request, response);
    }
    
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) 
            throws ServletException, IOException {
        
        request.setCharacterEncoding("UTF-8");
        response.setCharacterEncoding("UTF-8");
        
        String pathInfo = request.getPathInfo();
        String action = pathInfo != null ? pathInfo.substring(1) : "list";
        
        // 获取当前用户
        HttpSession session = request.getSession();
        User currentUser = (User) session.getAttribute("currentUser");
        if (currentUser == null) {
            response.sendRedirect(request.getContextPath() + "/pages/common/login.jsp");
            return;
        }
        
        try {
            switch (action) {
                case "list":
                    handleList(request, response);
                    break;
                case "my-records":
                    handleMyRecords(request, response);
                    break;
                case "add":
                    handleAdd(request, response);
                    break;
                case "edit":
                    handleEdit(request, response);
                    break;
                case "update":
                    handleUpdate(request, response);
                    break;
                case "delete":
                    handleDelete(request, response);
                    break;
                case "batchDelete":
                    handleBatchDelete(request, response);
                    break;
                case "view":
                    handleView(request, response);
                    break;
                case "search":
                    handleSearch(request, response);
                    break;
                case "statistics":
                    handleStatistics(request, response);
                    break;
                case "followUp":
                    handleFollowUp(request, response);
                    break;
                default:
                    response.sendError(HttpServletResponse.SC_BAD_REQUEST, "无效的操作");
                    break;
            }
        } catch (Exception e) {
            e.printStackTrace();
            response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "服务器内部错误");
        }
    }
    
    /**
     * 处理健康记录列表请求（管理员）
     */
    private void handleList(HttpServletRequest request, HttpServletResponse response) 
            throws ServletException, IOException {
        
        User currentUser = (User) request.getSession().getAttribute("currentUser");
        if (!"admin".equals(currentUser.getUserType())) {
            response.sendRedirect(request.getContextPath() + "/pages/common/unauthorized.jsp");
            return;
        }
        
        // 获取分页参数
        int currentPage = 1;
        int pageSize = 10;
        
        String pageStr = request.getParameter("page");
        String sizeStr = request.getParameter("size");
        
        if (pageStr != null && !pageStr.isEmpty()) {
            try {
                currentPage = Integer.parseInt(pageStr);
            } catch (NumberFormatException e) {
                currentPage = 1;
            }
        }
        
        if (sizeStr != null && !sizeStr.isEmpty()) {
            try {
                pageSize = Integer.parseInt(sizeStr);
            } catch (NumberFormatException e) {
                pageSize = 10;
            }
        }
        
        // 获取健康记录列表
        PageResult<HealthRecord> pageResult = healthRecordService.getHealthRecordsByPage(currentPage, pageSize);
        
        request.setAttribute("pageResult", pageResult);
        request.setAttribute("currentPage", currentPage);
        request.setAttribute("pageSize", pageSize);
        
        request.getRequestDispatcher("/pages/admin/health-record-list.jsp").forward(request, response);
    }
    
    /**
     * 处理我的宠物健康记录请求（用户）
     */
    private void handleMyRecords(HttpServletRequest request, HttpServletResponse response) 
            throws ServletException, IOException {
        
        User currentUser = (User) request.getSession().getAttribute("currentUser");

        // 获取分页参数
        int currentPage = 1;
        int pageSize = 10;
        
        String pageStr = request.getParameter("page");
        String sizeStr = request.getParameter("size");
        
        if (pageStr != null && !pageStr.isEmpty()) {
            try {
                currentPage = Integer.parseInt(pageStr);
            } catch (NumberFormatException e) {
                currentPage = 1;
            }
        }
        
        if (sizeStr != null && !sizeStr.isEmpty()) {
            try {
                pageSize = Integer.parseInt(sizeStr);
            } catch (NumberFormatException e) {
                pageSize = 10;
            }
        }
        
        // 获取用户宠物的健康记录
        PageResult<HealthRecord> pageResult = healthRecordService.getHealthRecordsByOwnerIdAndPage(
                currentUser.getUserId(), currentPage, pageSize);
        
        request.setAttribute("pageResult", pageResult);
        request.setAttribute("currentPage", currentPage);
        request.setAttribute("pageSize", pageSize);
        
        request.getRequestDispatcher("/pages/user/health-record-list.jsp").forward(request, response);
    }
    
    /**
     * 处理添加健康记录请求
     */
    private void handleAdd(HttpServletRequest request, HttpServletResponse response) 
            throws ServletException, IOException {
        
        User currentUser = (User) request.getSession().getAttribute("currentUser");
        
        if ("GET".equalsIgnoreCase(request.getMethod())) {
            // 显示添加表单
            if (!"admin".equals(currentUser.getUserType())) {
                response.sendRedirect(request.getContextPath() + "/pages/common/unauthorized.jsp");
                return;
            }
            
            // 获取所有宠物列表供选择
            List<Pet> pets = petService.getAllPets();
            request.setAttribute("pets", pets);
            
            request.getRequestDispatcher("/pages/admin/health-record-add.jsp").forward(request, response);
            return;
        }
        
        // 处理POST请求 - 添加健康记录
        if (!"admin".equals(currentUser.getUserType())) {
            response.sendRedirect(request.getContextPath() + "/pages/common/unauthorized.jsp");
            return;
        }
        
        // 获取表单参数
        String petIdStr = request.getParameter("petId");
        String visitDateStr = request.getParameter("visitDate");
        String symptoms = request.getParameter("symptoms");
        String diagnosis = request.getParameter("diagnosis");
        String treatment = request.getParameter("treatment");
        String medication = request.getParameter("medication");
        String doctorName = request.getParameter("doctorName");
        String nextVisitDateStr = request.getParameter("nextVisitDate");
        String costStr = request.getParameter("cost");
        String notes = request.getParameter("notes");
        
        // 创建健康记录对象
        HealthRecord healthRecord = new HealthRecord();
        
        try {
            if (petIdStr != null && !petIdStr.isEmpty()) {
                healthRecord.setPetId(Integer.parseInt(petIdStr));
            }
            
            if (visitDateStr != null && !visitDateStr.isEmpty()) {
                healthRecord.setVisitDate(Date.valueOf(visitDateStr));
            }
            
            healthRecord.setSymptoms(symptoms);
            healthRecord.setDiagnosis(diagnosis);
            healthRecord.setTreatment(treatment);
            healthRecord.setMedication(medication);
            healthRecord.setDoctorName(doctorName);
            
            if (nextVisitDateStr != null && !nextVisitDateStr.isEmpty()) {
                healthRecord.setNextVisitDate(Date.valueOf(nextVisitDateStr));
            }
            
            if (costStr != null && !costStr.isEmpty()) {
                healthRecord.setCost(new BigDecimal(costStr));
            }
            
            healthRecord.setNotes(notes);
            
        } catch (Exception e) {
            request.setAttribute("error", "参数格式错误");
            request.setAttribute("healthRecord", healthRecord);
            List<Pet> pets = petService.getAllPets();
            request.setAttribute("pets", pets);
            request.getRequestDispatcher("/pages/admin/health-record-add.jsp").forward(request, response);
            return;
        }
        
        // 添加健康记录
        if (healthRecordService.addHealthRecord(healthRecord)) {
            try {
                String successMsg = URLEncoder.encode("添加成功", "UTF-8");
                response.sendRedirect(request.getContextPath() + "/health/list?success=" + successMsg);
            } catch (Exception e) {
                response.sendRedirect(request.getContextPath() + "/health/list");
            }
        } else {
            request.setAttribute("error", "添加失败");
            request.setAttribute("healthRecord", healthRecord);
            List<Pet> pets = petService.getAllPets();
            request.setAttribute("pets", pets);
            request.getRequestDispatcher("/pages/admin/health-record-add.jsp").forward(request, response);
        }
    }

    /**
     * 处理编辑健康记录请求
     */
    private void handleEdit(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {

        User currentUser = (User) request.getSession().getAttribute("currentUser");
        String recordIdStr = request.getParameter("id");

        if (recordIdStr == null || recordIdStr.isEmpty()) {
            response.sendError(HttpServletResponse.SC_BAD_REQUEST, "记录ID不能为空");
            return;
        }

        try {
            Integer recordId = Integer.parseInt(recordIdStr);
            HealthRecord healthRecord = healthRecordService.getHealthRecordById(recordId);

            if (healthRecord == null) {
                response.sendError(HttpServletResponse.SC_NOT_FOUND, "健康记录不存在");
                return;
            }

            // 检查权限
            if (!healthRecordService.hasPermission(recordId, currentUser.getUserId(), "admin".equals(currentUser.getUserType()))) {
                response.sendRedirect(request.getContextPath() + "/pages/common/unauthorized.jsp");
                return;
            }

            // 只有管理员可以编辑
            if (!"admin".equals(currentUser.getUserType())) {
                response.sendRedirect(request.getContextPath() + "/pages/common/unauthorized.jsp");
                return;
            }

            request.setAttribute("healthRecord", healthRecord);

            // 获取所有宠物列表供选择
            List<Pet> pets = petService.getAllPets();
            request.setAttribute("pets", pets);

            request.getRequestDispatcher("/pages/admin/health-record-edit.jsp").forward(request, response);

        } catch (NumberFormatException e) {
            response.sendError(HttpServletResponse.SC_BAD_REQUEST, "记录ID格式错误");
        }
    }

    /**
     * 处理更新健康记录请求
     */
    private void handleUpdate(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {

        User currentUser = (User) request.getSession().getAttribute("currentUser");

        // 只有管理员可以更新
        if (!"admin".equals(currentUser.getUserType())) {
            response.sendRedirect(request.getContextPath() + "/pages/common/unauthorized.jsp");
            return;
        }

        // 获取表单参数
        String recordIdStr = request.getParameter("recordId");
        String petIdStr = request.getParameter("petId");
        String visitDateStr = request.getParameter("visitDate");
        String symptoms = request.getParameter("symptoms");
        String diagnosis = request.getParameter("diagnosis");
        String treatment = request.getParameter("treatment");
        String medication = request.getParameter("medication");
        String doctorName = request.getParameter("doctorName");
        String nextVisitDateStr = request.getParameter("nextVisitDate");
        String costStr = request.getParameter("cost");
        String notes = request.getParameter("notes");

        if (recordIdStr == null || recordIdStr.isEmpty()) {
            response.sendError(HttpServletResponse.SC_BAD_REQUEST, "记录ID不能为空");
            return;
        }

        // 创建健康记录对象
        HealthRecord healthRecord = new HealthRecord();

        try {
            healthRecord.setRecordId(Integer.parseInt(recordIdStr));

            if (petIdStr != null && !petIdStr.isEmpty()) {
                healthRecord.setPetId(Integer.parseInt(petIdStr));
            }

            if (visitDateStr != null && !visitDateStr.isEmpty()) {
                healthRecord.setVisitDate(Date.valueOf(visitDateStr));
            }

            healthRecord.setSymptoms(symptoms);
            healthRecord.setDiagnosis(diagnosis);
            healthRecord.setTreatment(treatment);
            healthRecord.setMedication(medication);
            healthRecord.setDoctorName(doctorName);

            if (nextVisitDateStr != null && !nextVisitDateStr.isEmpty()) {
                healthRecord.setNextVisitDate(Date.valueOf(nextVisitDateStr));
            }

            if (costStr != null && !costStr.isEmpty()) {
                healthRecord.setCost(new BigDecimal(costStr));
            }

            healthRecord.setNotes(notes);

        } catch (Exception e) {
            request.setAttribute("error", "参数格式错误");
            request.setAttribute("healthRecord", healthRecord);
            List<Pet> pets = petService.getAllPets();
            request.setAttribute("pets", pets);
            request.getRequestDispatcher("/pages/admin/health-record-edit.jsp").forward(request, response);
            return;
        }

        // 检查权限
        if (!healthRecordService.hasPermission(healthRecord.getRecordId(), currentUser.getUserId(), true)) {
            response.sendRedirect(request.getContextPath() + "/pages/common/unauthorized.jsp");
            return;
        }

        // 更新健康记录
        if (healthRecordService.updateHealthRecord(healthRecord)) {
            try {
                String successMsg = URLEncoder.encode("更新成功", "UTF-8");
                response.sendRedirect(request.getContextPath() + "/health/list?success=" + successMsg);
            } catch (Exception e) {
                response.sendRedirect(request.getContextPath() + "/health/list");
            }
        } else {
            request.setAttribute("error", "更新失败");
            request.setAttribute("healthRecord", healthRecord);
            List<Pet> pets = petService.getAllPets();
            request.setAttribute("pets", pets);
            request.getRequestDispatcher("/pages/admin/health-record-edit.jsp").forward(request, response);
        }
    }

    /**
     * 处理删除健康记录请求
     */
    private void handleDelete(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {

        User currentUser = (User) request.getSession().getAttribute("currentUser");
        String recordIdStr = request.getParameter("id");

        if (recordIdStr == null || recordIdStr.isEmpty()) {
            response.sendError(HttpServletResponse.SC_BAD_REQUEST, "记录ID不能为空");
            return;
        }

        try {
            Integer recordId = Integer.parseInt(recordIdStr);

            // 检查权限
            if (!healthRecordService.hasPermission(recordId, currentUser.getUserId(), "admin".equals(currentUser.getUserType()))) {
                response.sendRedirect(request.getContextPath() + "/pages/common/unauthorized.jsp");
                return;
            }

            // 只有管理员可以删除
            if (!"admin".equals(currentUser.getUserType())) {
                response.sendRedirect(request.getContextPath() + "/pages/common/unauthorized.jsp");
                return;
            }

            if (healthRecordService.deleteHealthRecord(recordId)) {
                try {
                    String successMsg = URLEncoder.encode("删除成功", "UTF-8");
                    response.sendRedirect(request.getContextPath() + "/health/list?success=" + successMsg);
                } catch (Exception e) {
                    response.sendRedirect(request.getContextPath() + "/health/list");
                }
            } else {
                try {
                    String errorMsg = URLEncoder.encode("删除失败", "UTF-8");
                    response.sendRedirect(request.getContextPath() + "/health/list?error=" + errorMsg);
                } catch (Exception e) {
                    response.sendRedirect(request.getContextPath() + "/health/list");
                }
            }

        } catch (NumberFormatException e) {
            response.sendError(HttpServletResponse.SC_BAD_REQUEST, "记录ID格式错误");
        }
    }

    /**
     * 处理批量删除健康记录请求
     */
    private void handleBatchDelete(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {

        User currentUser = (User) request.getSession().getAttribute("currentUser");

        // 只有管理员可以批量删除
        if (!"admin".equals(currentUser.getUserType())) {
            response.sendRedirect(request.getContextPath() + "/pages/common/unauthorized.jsp");
            return;
        }

        String[] recordIdStrs = request.getParameterValues("recordIds");

        if (recordIdStrs == null || recordIdStrs.length == 0) {
            try {
                String errorMsg = URLEncoder.encode("请选择要删除的记录", "UTF-8");
                response.sendRedirect(request.getContextPath() + "/health/list?error=" + errorMsg);
            } catch (Exception e) {
                response.sendRedirect(request.getContextPath() + "/health/list");
            }
            return;
        }

        try {
            Integer[] recordIds = new Integer[recordIdStrs.length];
            for (int i = 0; i < recordIdStrs.length; i++) {
                recordIds[i] = Integer.parseInt(recordIdStrs[i]);
            }

            if (healthRecordService.batchDeleteHealthRecords(recordIds)) {
                try {
                    String successMsg = URLEncoder.encode("批量删除成功", "UTF-8");
                    response.sendRedirect(request.getContextPath() + "/health/list?success=" + successMsg);
                } catch (Exception e) {
                    response.sendRedirect(request.getContextPath() + "/health/list");
                }
            } else {
                try {
                    String errorMsg = URLEncoder.encode("批量删除失败", "UTF-8");
                    response.sendRedirect(request.getContextPath() + "/health/list?error=" + errorMsg);
                } catch (Exception e) {
                    response.sendRedirect(request.getContextPath() + "/health/list");
                }
            }

        } catch (NumberFormatException e) {
            try {
                String errorMsg = URLEncoder.encode("记录ID格式错误", "UTF-8");
                response.sendRedirect(request.getContextPath() + "/health/list?error=" + errorMsg);
            } catch (Exception ex) {
                response.sendRedirect(request.getContextPath() + "/health/list");
            }
        }
    }

    /**
     * 处理查看健康记录详情请求
     */
    private void handleView(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {

        User currentUser = (User) request.getSession().getAttribute("currentUser");
        String recordIdStr = request.getParameter("id");

        if (recordIdStr == null || recordIdStr.isEmpty()) {
            response.sendError(HttpServletResponse.SC_BAD_REQUEST, "记录ID不能为空");
            return;
        }

        try {
            Integer recordId = Integer.parseInt(recordIdStr);
            HealthRecord healthRecord = healthRecordService.getHealthRecordById(recordId);

            if (healthRecord == null) {
                response.sendError(HttpServletResponse.SC_NOT_FOUND, "健康记录不存在");
                return;
            }

            // 检查权限
            if (!healthRecordService.hasPermission(recordId, currentUser.getUserId(), "admin".equals(currentUser.getUserType()))) {
                response.sendRedirect(request.getContextPath() + "/pages/common/unauthorized.jsp");
                return;
            }

            request.setAttribute("healthRecord", healthRecord);

            String forwardUrl = "admin".equals(currentUser.getUserType()) ?
                "/pages/admin/health-record-view.jsp" : "/pages/user/health-record-view.jsp";
            request.getRequestDispatcher(forwardUrl).forward(request, response);

        } catch (NumberFormatException e) {
            response.sendError(HttpServletResponse.SC_BAD_REQUEST, "记录ID格式错误");
        }
    }

    /**
     * 处理搜索健康记录请求
     */
    private void handleSearch(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {

        User currentUser = (User) request.getSession().getAttribute("currentUser");

        // 获取搜索参数
        String petName = request.getParameter("petName");
        String diagnosis = request.getParameter("diagnosis");
        String doctorName = request.getParameter("doctorName");
        String visitDateStartStr = request.getParameter("visitDateStart");
        String visitDateEndStr = request.getParameter("visitDateEnd");

        // 获取分页参数
        int currentPage = 1;
        int pageSize = 10;

        String pageStr = request.getParameter("page");
        String sizeStr = request.getParameter("size");

        if (pageStr != null && !pageStr.isEmpty()) {
            try {
                currentPage = Integer.parseInt(pageStr);
            } catch (NumberFormatException e) {
                currentPage = 1;
            }
        }

        if (sizeStr != null && !sizeStr.isEmpty()) {
            try {
                pageSize = Integer.parseInt(sizeStr);
            } catch (NumberFormatException e) {
                pageSize = 10;
            }
        }

        // 转换日期参数
        Date visitDateStart = null;
        Date visitDateEnd = null;

        try {
            if (visitDateStartStr != null && !visitDateStartStr.isEmpty()) {
                visitDateStart = Date.valueOf(visitDateStartStr);
            }
            if (visitDateEndStr != null && !visitDateEndStr.isEmpty()) {
                visitDateEnd = Date.valueOf(visitDateEndStr);
            }
        } catch (IllegalArgumentException e) {
            request.setAttribute("error", "日期格式错误");
        }

        // 根据用户类型设置ownerId
        Integer ownerId = null;
        if (!"admin".equals(currentUser.getUserType())) {
            ownerId = currentUser.getUserId();
        }

        // 执行搜索
        PageResult<HealthRecord> pageResult = healthRecordService.searchHealthRecords(
                petName, diagnosis, doctorName, visitDateStart, visitDateEnd, ownerId, currentPage, pageSize);

        request.setAttribute("pageResult", pageResult);
        request.setAttribute("currentPage", currentPage);
        request.setAttribute("pageSize", pageSize);
        request.setAttribute("petName", petName);
        request.setAttribute("diagnosis", diagnosis);
        request.setAttribute("doctorName", doctorName);
        request.setAttribute("visitDateStart", visitDateStartStr);
        request.setAttribute("visitDateEnd", visitDateEndStr);

        String forwardUrl = "admin".equals(currentUser.getUserType()) ?
            "/pages/admin/health-record-list.jsp" : "/pages/user/health-record-list.jsp";
        request.getRequestDispatcher(forwardUrl).forward(request, response);
    }

    /**
     * 处理统计信息请求
     */
    private void handleStatistics(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {

        User currentUser = (User) request.getSession().getAttribute("currentUser");

        // 只有管理员可以查看统计信息
        if (!"admin".equals(currentUser.getUserType())) {
            response.sendRedirect(request.getContextPath() + "/pages/common/unauthorized.jsp");
            return;
        }

        // 获取统计数据
        long totalRecords = healthRecordService.getTotalHealthRecordsCount();
        List<HealthRecord> todayRecords = healthRecordService.getTodayHealthRecords();
        List<HealthRecord> followUpRecords = healthRecordService.getRecordsNeedingFollowUp();
        List<Object[]> doctorStatistics = healthRecordService.getDoctorStatistics();

        // 获取年份参数
        int year = java.time.Year.now().getValue();
        String yearStr = request.getParameter("year");
        if (yearStr != null && !yearStr.isEmpty()) {
            try {
                year = Integer.parseInt(yearStr);
            } catch (NumberFormatException e) {
                year = java.time.Year.now().getValue();
            }
        }

        List<Object[]> monthlyStatistics = healthRecordService.getMonthlyStatistics(year);

        request.setAttribute("totalRecords", totalRecords);
        request.setAttribute("todayRecords", todayRecords);
        request.setAttribute("followUpRecords", followUpRecords);
        request.setAttribute("doctorStatistics", doctorStatistics);
        request.setAttribute("monthlyStatistics", monthlyStatistics);
        request.setAttribute("currentYear", year);

        request.getRequestDispatcher("/pages/admin/health-record-statistics.jsp").forward(request, response);
    }

    /**
     * 处理复诊提醒请求
     */
    private void handleFollowUp(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {

        User currentUser = (User) request.getSession().getAttribute("currentUser");

        // 获取需要复诊的记录
        List<HealthRecord> followUpRecords;

        if ("admin".equals(currentUser.getUserType())) {
            // 管理员可以查看所有需要复诊的记录
            followUpRecords = healthRecordService.getRecordsNeedingFollowUp();
        } else {
            // 普通用户只能查看自己宠物的复诊记录
            List<HealthRecord> allRecords = healthRecordService.getHealthRecordsByOwnerId(currentUser.getUserId());
            followUpRecords = allRecords.stream()
                    .filter(record -> record.needsFollowUp())
                    .collect(Collectors.toList());
        }

        request.setAttribute("followUpRecords", followUpRecords);

        String forwardUrl = "admin".equals(currentUser.getUserType()) ?
            "/pages/admin/health-record-followup.jsp" : "/pages/user/health-record-followup.jsp";
        request.getRequestDispatcher(forwardUrl).forward(request, response);
    }
}
